#include"child_pthread.h"
#include"client.h"
#include"trans_file.h"
//子线程是用来上传下载文件的
void child_pthread_create(pthread_t* ppthid,Thread_Info_t* pti){
    pthread_create(ppthid,NULL,pthread_handle,pti);
}
void* pthread_handle(void* p1){
    //等待主线程发送token，若收到token表明子线程将开始工作
    Thread_Info_t* pti=(Thread_Info_t*)p1;
    train_state_t t,t1;
    train_off_t ot;
    bzero(&t1,sizeof(train_state_t));
    char token[100]={0};
    while(pti->notification==0);
    strcpy(token,pti->token);
    pti->notification=0;
    printf("Chile thread is ready\n");
    //子线程在工作之前先要使用token做一次登录，这样客户端才能识别
    t1.state=TOKEN;
    strcpy(t1.buf,token);
    printf("token值=%s\n",t1.buf);
    t1.data_len=4+strlen(t1.buf);
    //判断上传还是下载，给服务器发送带有state的小火车
    char cmd[128];
    char md5_str[100];
    while(1){
        bzero(cmd,128);
        while(pti->notification==0);//一直等待主线程发送任务
        strcpy(cmd,pti->command);
        pti->notification=0;
        //connect到服务器
        int sfd=socket(AF_INET,SOCK_STREAM,0);
        printf("sfd=%d\n",sfd);
        int ret=connect(sfd,(struct sockaddr *)&(pti->ser_addr),pti->len_of_ser_addr);
        //发送token值进行登录
        printf("子线程已连接\n");
        send_n(sfd,&t1.data_len,4);
        send_n(sfd,&t1.state,t.data_len);
        char file_name[256];
        int file_pos = 5 ;
        if(strncmp(cmd,"puts",4)) {
            printf("你奶奶的\n");
            while(bzero(file_name, 256),sscanf(cmd + file_pos,"%s", file_name ) == 1){
                file_pos += strlen(file_name) + 1; 
                send_session(sfd,&t,PUTS,file_name);//发文件名字
                printf("文件名字为%s\n",file_name);
                bzero(md5_str,100);
                Compute_file_md5(file_name,md5_str);
                printf("文件的md5值为%s\n",md5_str);
                send_session(sfd,&t,MD5,md5_str);
                if(upload(sfd, file_name) == 0){
                    printf(" file-> %s upload success\n", file_name);
                }else {
                    printf(" file-> %s upload failed\n", file_name);
                    //sendn(sfd,(char*)&flag,sizeof(int));
                }	
            }
        }else{
            while(bzero(file_name, 256), sscanf(cmd + file_pos,"%s", file_name) == 1){
                file_pos += strlen(file_name) + 1 ;
                send_session(sfd,&t,GETS,file_name);
                if(download(sfd,file_name,&ot)== 0){
                    printf("file -> %s download success \n", file_name);
                }else{
                    printf("file -> %s download failed \n", file_name);
                }
            }
        }
        close(sfd);
    }
}
